package cn.wang.service.sysadmin.Impl;

import cn.wang.dao.BaseDao;
import cn.wang.entity.sysadmin.Role;
import cn.wang.entity.sysadmin.User;
import cn.wang.service.sysadmin.UserService;
import cn.wang.utils.Encrypt;
import cn.wang.utils.MailUtils;
import cn.wang.utils.Pagination;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * Created by john on 2017/11/1.
 */

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private BaseDao<User, String> baseDao;
    @Autowired
    private BaseDao<Role, String> stringBaseDao;
    @Autowired
    private SimpleMailMessage message;
    @Autowired
    private JavaMailSender sender;
    //日志记录
    private Logger logger = Logger.getLogger(UserServiceImpl.class);

    @Override
    public Pagination findPage(int pageNo, int pageSize, User user) {
        String hql = "from User u where 1=1";
        long degree = user.getUserInfo().getDegree();
        //查询本部门数据
        if (degree == 3) {
            hql += " and u.createDept = '" + user.getDept().getId() + "'";
            System.out.println(hql);
            //查询本人数据
        } else if (degree == 4) {
            hql += " and u.createBy = '" + user.getId() + "'";
        }
        return baseDao.pageByHql(hql, pageNo, pageSize);
    }

    @Override
    public List<User> findAll() {
        return baseDao.getListByHQL("from User");
    }

    @Override
    public User findById(String id) {
        return baseDao.get(User.class, id);
    }

    @Override
    public void save(User model) {
        //保证邮箱不为空
        if (!model.getUserInfo().getEmail().isEmpty()) {
            //一对一相互关联
            // model.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            //设置密码
            model.setPassWord(Encrypt.md5(model.getUserName(), model.getUserName()));
            model.getUserInfo().setUser(model);
            // model.setUserInfo(model.getUserInfo());
            //设置激活码
            model.setCode(UUID.randomUUID().toString());
            baseDao.save(model);
            //保存成功后发送邮件
            //准备 1发送地址 2主题 3内容
            String toaddrss = model.getUserInfo().getEmail();
            String subject = "欢迎来到重庆京东方";
            String text = "<a href=http://localhost:88/sysadmin/userAction_activty?code=" + model.getCode() + "&id=" + model.getId() + ">点击激活</a>";
            //新开线程 解决网络延迟 断网 是重复加载 带来体验差
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean isok = false;
                    int count = 0;
                    while (count < 3 && !isok) {
                        try {

                            // MailUtils.sendMail(toaddrss, subject, text);
                            logger.info("发送成功");
                            MimeMessage message = sender.createMimeMessage();
                            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
                            messageHelper.setFrom("15282723985@sina.cn");
                            messageHelper.setTo(toaddrss);
                            messageHelper.setSubject(subject);
                            messageHelper.setText(text, true);//表示为HTML文件
                            sender.send(message);
                            isok = true;
                            //System.out.println("发送成功");

                        } catch ( RuntimeException e ) {
                            try {
                                Thread.sleep(5000);
                                System.out.println("发送邮件失败正在尝第[" + count + "]次发送....");
                                logger.error("发送邮件失败正在尝第[" + count + "]次发送....");
                            } catch ( InterruptedException e1 ) {
                                e1.printStackTrace();
                            }
                            count++;
                        } catch ( MessagingException e ) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }

    }

    @Override
    public void delete(String[] ids) {
        for (String id : ids) {
            baseDao.deleteById(User.class, id);
        }
    }

    @Override
    public void update(User model) {
        User olduser = baseDao.get(User.class, model.getId());
        olduser.setDept(model.getDept());
        olduser.setUserName(model.getUserName());
        olduser.setState(model.getState());

        baseDao.update(olduser);
    }

    @Override
    public void updateRole(String id, String[] roleIds) {
        User user = baseDao.get(User.class, id);
        Set<Role> roleSet = new HashSet<>(roleIds.length);
        for (String roleid : roleIds) {
            Role role = stringBaseDao.get(Role.class, roleid);
            roleSet.add(role);
        }
        user.setRoleSet(roleSet);
        baseDao.update(user);
    }

    @Override
    public User findByUserName(String username) {
        return baseDao.getByHQL("from User where userName=?", username);
    }

    @Override
    public User activty(User model) {
        model = baseDao.getByHQL("from User u where u.id=? and u.code=? ", model.getId(), model.getCode());

        if (model != null) {

            model.setState(1);
            model.setCode(null);
            baseDao.update(model);
        }
        return model;
    }
}
